package vn.igolf.golf;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class GolfCourse {
	
	private String name;
	private int par;
	private int index;
	private ArrayList<String> tees = new ArrayList<String>();
	private ArrayList<Hole> holes = new ArrayList<Hole>();
	
	private static String NAME = "name";
	private static String TEES = "tees";
	private static String HOLE = "hole";

	public GolfCourse () {
	}
	
	public static GolfCourse readFromFile (String filename) {
		GolfCourse ret = new GolfCourse();
		
	    try {
	    	BufferedReader br = new BufferedReader(new FileReader(filename));
	        String line = null;
	        while ((line=br.readLine()) != null) {
	        	line = line.trim().toLowerCase();
	        	if(line.length()==0) continue;
	        	if(line.charAt(0)!='#') continue;
	        	line = line.substring(1).trim();
	        	if(line.equals(NAME)) ret.readNameFromFile ( br);
	        	if(line.equals(TEES)) ret.readTeesFromFile ( br);
	        	if(line.equals(HOLE)) ret.readHoleFromFile ( br);
	        }
	        
	        br.close();
	    }catch (Exception e) {
			// TODO: handle exception
	    }
		return ret;
	}
	
	public void readHoleFromFile (BufferedReader br) throws IOException {
		Hole hole = Hole.readHoleFromFile (br);
		addHole(hole);
	}
	
	public void readNameFromFile (BufferedReader br) throws IOException {
		setName( br.readLine() );
	}
	
	public void readTeesFromFile (BufferedReader br) throws IOException {
		String line = null;
		while ((line =br.readLine())!=null) {
			line = line.trim();
			if (line.length()==0) break;
			addTee(line);
		}
	}
	
	public void addTee (String tee) {
		tees.add(tee);
	}
	
	public void addHole (Hole hole) {
		holes.add(hole);
		par += hole.getPar();
	}
	
	public String toString () {
		StringBuffer sb = new StringBuffer();
		sb.append( name + "\n");
		sb.append( par + "\n");
		sb.append( tees + "\n");
		sb.append( holes + "\n");
		return sb.toString();
	}

	public int getPar() {
		return par;
	}

	public void setPar(int par) {
		this.par = par;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	public ArrayList<String> getTees() {
		return tees;
	}

	public void setTees(ArrayList<String> tees) {
		this.tees = tees;
	}

	public ArrayList<Hole> getHoles() {
		return holes;
	}

	public void setHoles(ArrayList<Hole> holes) {
		this.holes = holes;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public static void main(String[] args) {
		GolfCourse gc = GolfCourse.readFromFile("images/course/course.txt");
		System.out.println(gc);
	}
}
